// ignore_for_file: depend_on_referenced_packages

import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:photo_manager/photo_manager.dart';
import 'asset_page.dart';
import 'package:photo_manager_image_provider/photo_manager_image_provider.dart';
import 'package:image_picker/image_picker.dart';

enum LocalAssetType {
  common,
  image,
  video,
}

enum PickerImageSource {
  camera(0),
  album(1);

  final int value;
  const PickerImageSource(this.value);
}


typedef AssetChosedImageCallback = void Function(List<String> imagePaths)? ;
typedef AssetCallback = void Function(List<AssetEntity> assets);

class AssetTool {
  static Future<bool> requestPermission() async {
    PermissionState ps = await PhotoManager.requestPermissionExtend();
    return ps.isAuth;
  }

  static void openSetting() {
    PhotoManager.openSetting();
  }

  static Future<String?> ossUpload(File file) async {
    // String? result = await OssUploadManager.getInstance().upload(file);
    // return result;
    return "";
  }

  /// 拍照和拍摄
  static void selectPicker(
    BuildContext context, {
    required LocalAssetType type,
    int? maxVideoLength,
    AssetCallback? callback,
  }) async {
    if (type == LocalAssetType.image) {
      final pImage = await ImagePicker().pickImage(source: ImageSource.camera);
      if (pImage != null) {
        /// 转为Uint8List
        final Uint8List byteData = await pImage.readAsBytes();
        String title = "volvo_${DateTime.now()}.jpg";
        final AssetEntity? aEntity = await PhotoManager.editor.saveImage(byteData, title: title, filename: title);
        callback?.call(aEntity == null ? [] : [aEntity]);
      }
    } else if (type == LocalAssetType.video) {
      final pVideo = await ImagePicker().pickVideo(source: ImageSource.camera);
      if (pVideo != null) {
        /// 转为File
        File file = File(pVideo.path);
        String title = "volvo_${DateTime.now()}.mp4";
        final AssetEntity? aEntity = await PhotoManager.editor.saveVideo(file, title: title);
        callback?.call(aEntity == null ? [] : [aEntity]);
      }
    }

    // final AssetEntity? aEntity = await CameraPicker.pickFromCamera(
    //   context,
    //   pickerConfig: CameraPickerConfig(
    //     enableRecording: type == LocalAssetType.image ? false : true,
    //     onlyEnableRecording: type == LocalAssetType.image ? false : true,
    //     maximumRecordingDuration: Duration(
    //       seconds: maxVideoLength ?? 15,
    //     ),
    //   ),
    // );
    // callback?.call(aEntity == null ? [] : [aEntity]);
  }

  /// 相册中选择
  static void selectAsset(
    BuildContext context, {
    required LocalAssetType type,
    int? maxAssets,
    int? maxVideoLength,
    List<AssetEntity>? selectedAssets,
    AssetCallback? callback,
  }) async {
    bool isAuth = await AssetTool.requestPermission();

    if (isAuth) {
      final List<AssetEntity>? result = await Navigator.push(
        context,
        CupertinoPageRoute(
          builder: (context) => VolvoAssetPage(
            type: type,
            maxAssetCount: maxAssets ?? 9,
            maxVideoLength: maxVideoLength ?? 15,
            selectedCallback: callback,
          ),
        ),
      );
      callback?.call(result ?? []);
    } else {
      /// 没有全线
      AssetTool.openSetting();
    }
  }

  /// 显示获取图片的方式: 相机, 从相册获取
  // static void showImagePickerSheet(BuildContext context, {int? maxCount, required AssetChosedImageCallback? onChosedImage}) async {
  //   VolvoActionSheet.showTextAction(
  //     context: context,
  //     actions: [
  //       ActionSheetTextItem(BaseKey.photograph.getString(context)),
  //       ActionSheetTextItem(BaseKey.photoAlbum.getString(context)),
  //     ],
  //     clickCallBack: (int index) {
  //       if (index == PickerImageSource.camera.value) {
  //         openCamera(context, onChosedImage: onChosedImage);
  //       } else if (index == PickerImageSource.album.value) {
  //         openAlbum(maxCount: maxCount, onChosedImage: onChosedImage);
  //       }
  //     },
  //   );
  // }

  // static void openCamera(BuildContext context, {Function(List<String>)? onChosedImage}) {
  //   PermissionService().checkPermission(PermissionType.camera).then((status) {
  //     if (status == PermissionAuthStatus.isGranted) {
  //       ImagePicker().pickImage(source: ImageSource.camera).then((pImage) {
  //         if (pImage != null) {
  //           onChosedImage?.call([pImage.path]);
  //         }
  //       });
  //     } else {
  //       VolvoPermissionSheet.showDeniedSheet(context, PermissionSheetType.camera);
  //     }
  //   });
  // }

  static void openAlbum({int? maxCount, Function(List<String>)? onChosedImage}) {
    ImagePicker().pickMultiImage().then((pImages) {
      if (maxCount != null && maxCount > 0) {
        onChosedImage?.call(pImages.sublist(0, min(maxCount, pImages.length)).map((e) => e.path).toList());
      } else {
        onChosedImage?.call(pImages.map((e) => e.path).toList());
      }
    });
  }
}

class ImageEntity {
  String id;
  int typeInt;
  int width;
  int height;
  String? url; // 上传oss链接
  int? type; // 图片默认为2

  ImageEntity({
    required this.id,
    required this.typeInt,
    required this.width,
    required this.height,
    this.url,
    this.type,
  });

  ImageEntity copyWith({
    String? id,
    int? typeInt,
    int? width,
    int? height,
    String? url,
    int? type,
  }) =>
      ImageEntity(
        id: id ?? this.id,
        typeInt: typeInt ?? this.typeInt,
        width: width ?? this.width,
        height: height ?? this.height,
        url: url ?? this.url,
        type: type ?? this.type,
      );

  factory ImageEntity.fromJson(Map<String, dynamic> json) => ImageEntity(
        id: json["id"],
        typeInt: json["typeInt"],
        width: json["width"],
        height: json["height"],
        url: json["url"],
        type: json["type"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "typeInt": typeInt,
        "width": width,
        "height": height,
        "url": url,
        "type": type,
      };
}
